#include "usbd_core.h"
#include "usbd_cdc.h"

/*!< endpoint address */
#define CDC_IN_EP  0x81
#define CDC_OUT_EP 0x02
#define CDC_INT_EP 0x83

#define USBD_VID           0xFFFF
#define USBD_PID           0xFFFF
#define USBD_MAX_POWER     100
#define USBD_LANGID_STRING 1033

/*!< config descriptor size */
#define USB_CONFIG_SIZE (9 + CDC_ACM_DESCRIPTOR_LEN)

#ifdef CONFIG_USB_HS
#define CDC_MAX_MPS 512
#else
#define CDC_MAX_MPS 64
#endif

#define PACK_HEAD_LEN   (2)
struct rw_ctrl_handle
{
    uint8_t *txbuf;// 循环
    uint8_t *rxbuf;// 非循环
    uint16_t tx_rofs;
    uint16_t tx_wofs;
    uint16_t rx_rofs;
    uint16_t rx_wofs;
};

const uint8_t request_head[] = {0x77,0xAA};

static struct rw_ctrl_handle* g_rw_handle;
/*!< global descriptor */
static const uint8_t cdc_descriptor[] = {
    USB_DEVICE_DESCRIPTOR_INIT(USB_2_0, 0xEF, 0x02, 0x01, USBD_VID, USBD_PID, 0x0100, 0x01),
    USB_CONFIG_DESCRIPTOR_INIT(USB_CONFIG_SIZE, 0x02, 0x01, USB_CONFIG_BUS_POWERED, USBD_MAX_POWER),
    CDC_ACM_DESCRIPTOR_INIT(0x00, CDC_INT_EP, CDC_OUT_EP, CDC_IN_EP, CDC_MAX_MPS, 0x02),
    ///////////////////////////////////////
    /// string0 descriptor
    ///////////////////////////////////////
    USB_LANGID_INIT(USBD_LANGID_STRING),
    ///////////////////////////////////////
    /// string1 descriptor
    ///////////////////////////////////////
    0x14,                       /* bLength */
    USB_DESCRIPTOR_TYPE_STRING, /* bDescriptorType */
    'C', 0x00,                  /* wcChar0 */
    'h', 0x00,                  /* wcChar1 */
    'e', 0x00,                  /* wcChar2 */
    'r', 0x00,                  /* wcChar3 */
    'r', 0x00,                  /* wcChar4 */
    'y', 0x00,                  /* wcChar5 */
    'U', 0x00,                  /* wcChar6 */
    'S', 0x00,                  /* wcChar7 */
    'B', 0x00,                  /* wcChar8 */
    ///////////////////////////////////////
    /// string2 descriptor
    ///////////////////////////////////////
    0x26,                       /* bLength */
    USB_DESCRIPTOR_TYPE_STRING, /* bDescriptorType */
    'C', 0x00,                  /* wcChar0 */
    'h', 0x00,                  /* wcChar1 */
    'e', 0x00,                  /* wcChar2 */
    'r', 0x00,                  /* wcChar3 */
    'r', 0x00,                  /* wcChar4 */
    'y', 0x00,                  /* wcChar5 */
    'U', 0x00,                  /* wcChar6 */
    'S', 0x00,                  /* wcChar7 */
    'B', 0x00,                  /* wcChar8 */
    ' ', 0x00,                  /* wcChar9 */
    'C', 0x00,                  /* wcChar10 */
    'D', 0x00,                  /* wcChar11 */
    'C', 0x00,                  /* wcChar12 */
    ' ', 0x00,                  /* wcChar13 */
    'D', 0x00,                  /* wcChar14 */
    'E', 0x00,                  /* wcChar15 */
    'M', 0x00,                  /* wcChar16 */
    'O', 0x00,                  /* wcChar17 */
    ///////////////////////////////////////
    /// string3 descriptor
    ///////////////////////////////////////
    0x16,                       /* bLength */
    USB_DESCRIPTOR_TYPE_STRING, /* bDescriptorType */
    '2', 0x00,                  /* wcChar0 */
    '0', 0x00,                  /* wcChar1 */
    '2', 0x00,                  /* wcChar2 */
    '2', 0x00,                  /* wcChar3 */
    '1', 0x00,                  /* wcChar4 */
    '2', 0x00,                  /* wcChar5 */
    '3', 0x00,                  /* wcChar6 */
    '4', 0x00,                  /* wcChar7 */
    '5', 0x00,                  /* wcChar8 */
    '6', 0x00,                  /* wcChar9 */
#ifdef CONFIG_USB_HS
    ///////////////////////////////////////
    /// device qualifier descriptor
    ///////////////////////////////////////
    0x0a,
    USB_DESCRIPTOR_TYPE_DEVICE_QUALIFIER,
    0x00,
    0x02,
    0x02,
    0x02,
    0x01,
    0x40,
    0x01,
    0x00,
#endif
    0x00
};


#define USB_MSG_BUFF_SIZE   1024

#define USB_RW_BUFF_SIZE    2048
USB_NOCACHE_RAM_SECTION USB_MEM_ALIGNX uint8_t read_buffer[USB_RW_BUFF_SIZE];
USB_NOCACHE_RAM_SECTION USB_MEM_ALIGNX uint8_t write_buffer[USB_RW_BUFF_SIZE];

volatile bool ep_tx_busy_flag = false;

#ifdef CONFIG_USB_HS
#define CDC_MAX_MPS 512
#else
#define CDC_MAX_MPS 64
#endif

static void usbd_event_handler(uint8_t busid, uint8_t event)
{
    switch (event) {
        case USBD_EVENT_RESET:
            break;
        case USBD_EVENT_CONNECTED:
            break;
        case USBD_EVENT_DISCONNECTED:
            break;
        case USBD_EVENT_RESUME:
            break;
        case USBD_EVENT_SUSPEND:
            break;
        case USBD_EVENT_CONFIGURED:
            ep_tx_busy_flag = false;
            /* setup first out ep read transfer */
            usbd_ep_start_read(busid, CDC_OUT_EP, read_buffer, 2048);
            break;
        case USBD_EVENT_SET_REMOTE_WAKEUP:
            break;
        case USBD_EVENT_CLR_REMOTE_WAKEUP:
            break;

        default:
            break;
    }
}

void usbd_cdc_acm_bulk_out(uint8_t busid, uint8_t ep, uint32_t nbytes)
{
    USB_LOG_RAW("slave read len:%d\r\n", nbytes);
    
    // TODO
    memcpy(&g_rw_handle->rxbuf[g_rw_handle->rx_wofs],read_buffer,nbytes);
    g_rw_handle->rx_wofs += nbytes;
    /* setup next out ep read transfer */
    usbd_ep_start_read(busid, CDC_OUT_EP, read_buffer, 2048);
}

void usbd_cdc_acm_bulk_in(uint8_t busid, uint8_t ep, uint32_t nbytes)
{
    // USB_LOG_RAW("actual in len:%d\r\n", nbytes);
    USB_LOG_RAW("slave out len:%d\r\n", nbytes);
    if ((nbytes % CDC_MAX_MPS) == 0 && nbytes) {
        /* send zlp */
        usbd_ep_start_write(busid, CDC_IN_EP, NULL, 0);
    } else {
        ep_tx_busy_flag = false;
    }
}

/*!< endpoint call back */
struct usbd_endpoint cdc_out_ep = {
    .ep_addr = CDC_OUT_EP,
    .ep_cb = usbd_cdc_acm_bulk_out
};

struct usbd_endpoint cdc_in_ep = {
    .ep_addr = CDC_IN_EP,
    .ep_cb = usbd_cdc_acm_bulk_in
};

static struct usbd_interface intf0;
static struct usbd_interface intf1;



void cdc_acm_init_xxx(uint8_t busid, uint32_t reg_base)
{
    g_rw_handle = usb_malloc(sizeof(struct rw_ctrl_handle));
    memset(g_rw_handle,0,sizeof(struct rw_ctrl_handle));
    g_rw_handle->rxbuf = usb_malloc(USB_MSG_BUFF_SIZE);
    g_rw_handle->txbuf = usb_malloc(USB_MSG_BUFF_SIZE);

    usbd_desc_register(busid, cdc_descriptor);
    usbd_add_interface(busid, usbd_cdc_acm_init_intf(busid, &intf0));
    usbd_add_interface(busid, usbd_cdc_acm_init_intf(busid, &intf1));
    usbd_add_endpoint(busid, &cdc_out_ep);
    usbd_add_endpoint(busid, &cdc_in_ep);
    usbd_initialize(busid, reg_base, usbd_event_handler);
}

volatile uint8_t dtr_enable = 0;

void usbd_cdc_acm_set_dtr(uint8_t busid, uint8_t intf, bool dtr)
{
    if (dtr) {
        dtr_enable = 1;
    } else {
        dtr_enable = 0;
    }
}


static int match_usb_msg_head(uint8_t* recv_data,uint16_t recv_len,uint16_t* pkg_len)
{
    if(0 == memcmp(recv_data,request_head,sizeof(request_head)))
    {
        if(recv_len < 6)
        {
            *pkg_len =  USB_MSG_BUFF_SIZE;
        }else
        {
            *pkg_len = (recv_data[4]|recv_data[5]<<8);
        }
        return 1;
    }else
    {
        return 0;
    }
}

static int usb_msg_sum_check(uint8_t* packet_data,uint16_t len)
{
    uint8_t sum = 0;
    for(int i = 0; i < len-1; i++)
    {
        sum += packet_data[i];
    }
    if(sum == packet_data[len-1])
    {
        return 1;
    }
    return 0;
}
void usb_write_process(uint8_t busid)
{
    int write_len;
    int p_len;
    if(g_rw_handle->tx_wofs != g_rw_handle->tx_rofs && ep_tx_busy_flag == false)
    {
        ep_tx_busy_flag = true;
        if(g_rw_handle->tx_wofs < g_rw_handle->tx_rofs)
        {
            p_len = USB_MSG_BUFF_SIZE - g_rw_handle->tx_rofs;
            memcpy(write_buffer,&g_rw_handle->txbuf[g_rw_handle->tx_rofs],p_len);
            memcpy(&write_buffer[p_len],g_rw_handle->txbuf,g_rw_handle->tx_wofs);

            write_len = p_len + g_rw_handle->tx_wofs;
        }else
        {
            write_len = g_rw_handle->tx_wofs - g_rw_handle->tx_rofs;
            memcpy(write_buffer,&g_rw_handle->txbuf[g_rw_handle->tx_rofs],write_len);
        }
        g_rw_handle->tx_rofs = g_rw_handle->tx_wofs;
        
        usbd_ep_start_write(busid, CDC_IN_EP, write_buffer, write_len);
    }
}

extern void usb_recv_msg_deal(uint8_t* data,uint16_t len);
void usb_recv_process()
{
    uint16_t pkg_len;
    while (g_rw_handle->rx_wofs - g_rw_handle->rx_rofs > PACK_HEAD_LEN)
    {
        if(match_usb_msg_head(g_rw_handle->rxbuf+g_rw_handle->rx_rofs,(g_rw_handle->rx_wofs-g_rw_handle->rx_rofs),&pkg_len))
        {
            if(g_rw_handle->rx_wofs - g_rw_handle->rx_rofs >= pkg_len)
            {
                if(usb_msg_sum_check(g_rw_handle->rxbuf+g_rw_handle->rx_rofs,pkg_len))
                {
                    usb_recv_msg_deal(g_rw_handle->rxbuf+g_rw_handle->rx_rofs+sizeof(request_head),pkg_len-sizeof(request_head)-1);
                    g_rw_handle->rx_rofs += pkg_len;
                }else
                {
                    g_rw_handle->rx_wofs = 0;
                    break;
                }
            }else
            {
                break;
            }
        }else
        {
            g_rw_handle->rx_wofs = 0;
            break;
        }
    }

    if(g_rw_handle->rx_rofs)
    {
        g_rw_handle->rx_wofs -= g_rw_handle->rx_rofs;
        if(g_rw_handle->rx_wofs)memcpy(g_rw_handle->rxbuf,(g_rw_handle->rxbuf+g_rw_handle->rx_rofs),g_rw_handle->rx_wofs);
        g_rw_handle->rx_rofs = 0;
    }
    
}


void put_pkg_to_ringbuf(uint8_t *pkg, uint16_t len)
{
    uint16_t p_len;
    if(g_rw_handle->tx_wofs + len > USB_MSG_BUFF_SIZE && (g_rw_handle->tx_wofs + len)%USB_MSG_BUFF_SIZE > g_rw_handle->tx_rofs)
    {
        USB_LOG_RAW("ringbuff flow\n");
        return;
    }
    if(g_rw_handle->tx_wofs + len >= USB_MSG_BUFF_SIZE){
        p_len = USB_MSG_BUFF_SIZE - g_rw_handle->tx_wofs;
        memcpy(&g_rw_handle->txbuf[g_rw_handle->tx_wofs], pkg, p_len);
        memcpy(g_rw_handle->txbuf,&pkg[p_len],len-p_len);
        g_rw_handle->tx_wofs = len-p_len;
    }else{
        memcpy(&g_rw_handle->txbuf[g_rw_handle->tx_wofs], pkg, len);
        g_rw_handle->tx_wofs += len;
    }
}

void cdc_acm_device_run(uint8_t busid)
{
    usb_recv_process();
    usb_write_process(busid);
}


